<template>
    <div class="search-box">
        <div class="flex">
            <div style="color: black">
                <el-icon>
                    <Search />
                </el-icon>
                <span>筛选搜索</span>
            </div>
            <div>
                <el-button @click="resetForm">重置</el-button>
                <el-button @click="submitFn" type="primary">查询搜索</el-button>
            </div>
        </div>
        <div style="padding-top: 20px">
            <el-form @submit.prevent="submitFn" ref="searchFormRef" :model="listParams">
                <el-form-item prop="keyword" label="账号/姓名:" label-width="200px">
                    <el-input v-model="listParams.keyword"></el-input>
                </el-form-item>
            </el-form>
        </div>
    </div>

    <div class="add-box">
        <el-button type="primary" @click="addUser">添加</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="日期" width="180"></el-table-column>
        <el-table-column prop="note" label="账号" width="180"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="createTime" label="添加时间" width="200">
            <template #default="scope">
                {{ fomatDate(scope.row.createTime) }}
            </template>
        </el-table-column>
        <el-table-column prop="loginTime" label="最后登录" width="200">
            <template #default="scope">
                {{ fomatDate(scope.row.loginTime) }}
            </template>
        </el-table-column>
        <el-table-column label="是否启用" width="240">
            <template #default="scope">
                <el-switch
                    v-model="scope.row.status"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeHandle(scope.row)"
                />
            </template>
        </el-table-column>
        <el-table-column prop="username" label="操作" width="250">
            <template #default="scope">
                <el-button type="primary" @click="handleEdit(scope.row.id)">分配角色</el-button>
                <el-button type="primary" @click="handleDelete(scope.row.id)">编辑</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 需要汉化 -->
    <ElConfigProvider :locale="zhCn">
        <el-pagination
            background
            v-model:currentPage="listParams.pageNum"
            @size-change="pageSizeChagne"
            @current-change="currentChange"
            v-model:page-size="listParams.pageSize"
            layout="total,prev,sizes,prev, pager,next,jumper"
            :total="total"
        />
    </ElConfigProvider>

    <EditUserVue :show="showEditUser" @hide2="hideDialog" @refresh="getList()" :data="editId" />

    <AllocRoleVue :show="showAllocRole" @hide="hideAllocRole" :data="allocRoleId" />
</template>

<script setup lang="ts">
import { user } from '@/api/index';
import { reactive, ref, toRefs } from 'vue';
import { fomatDate } from '@/utils';
import { ElMessage, FormInstance } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { ElConfigProvider } from 'element-plus';
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
import EditUserVue from '@/components/EditUser.vue';
import AllocRoleVue from '@/components/AllocRole.vue';

const hideAllocRole = () => {
    showAllocRole.value = false;
};

// 分配角色按钮
const handleEdit = (id: number) => {
    showAllocRole.value = true;
    allocRoleId.value = id;
};
// 获取id
const handleDelete = (id: number) => {
    // 编辑功能的一般流程：
    // 1.从服务器获取旧的数据展示在页面中
    // 2.在表单里面修改完毕
    // 3.把最新的数据 向服务器发请求 同步到服务器
    // 向服务器获取数据，是在这里获取了再传入 子组件(EditUser)
    // 还是 把id 传递给 子组件，让它自己内部实现请求 ---> 用这种
    // 这部分获取数据并渲染的代码，是完全可以被我们封闭在组件内，不会有任何的改变
    // 就需要把一个id传入 子组件(EditUser)
    editId.value = id;
    // 把编辑框显示出来
    showEditUser.value = true;
};
// 获取角色指定的id
const allocRoleId = ref(0);

// 点击编辑需要的id
const editId = ref(0);

interface IState {
    tableData: IUserModel[];
    listParams: user;
    total: number;
    totalPage: number;
}

const state = reactive<IState>({
    tableData: [],
    listParams: {
        keyword: '',
        pageNum: 1,
        pageSize: 10,
    },
    total: 0,
    totalPage: 0,
});

const searchFormRef = ref<FormInstance>();

const showEditUser = ref(false);

// 分配角色的组件是否显示
const showAllocRole = ref(false);

const getList = () => {
    // 搜索跟之前第一次请求的不同就是 搜索要带 输入框里面的数据
    user.getUserListApi(state.listParams).then(res => {
        if (res.code === 200) {
            state.tableData = res.data.list;

            state.total = res.data.total;
            state.totalPage = res.data.totalPage;
            // console.log(res.data.totalPage);
        }
    });
};

getList();
// 修改用户状态
const changeHandle = (row: IUserModel) => {
    user.updateUserStatusApi({ id: row.id, status: row.status })
        .then(res => {
            ElMessage({
                message: res.message,
                type: res.code === 200 ? 'success' : 'error',
            });
        })
        .catch(err => {
            // 请求失败会走catch
            // 把修改按钮回复之前的状态
            // 方式一
            // row.status = row.status == 1 ? 0 : 1
            let target = state.tableData.find(item => item.id === row.id);
            target && (target.status = row.status === 1 ? 0 : 1);
        });
};
// 重置功能的实现：
// 1. 点击事件
// 2. 需要给el-from表单组件添加一个ref属性，得到该组件的实例
// 3. 点击的时候调用 组件实例的resetFields方法进行重置
// 4. 前提是 给 el-from 设置了 model 属性
// 5. 还需要给 el-form-item 设置相应的 prop 属性
const resetForm = () => {
    searchFormRef.value?.resetFields();
};

// 一次显示多少页
const pageSizeChagne = (value: number) => {
    getList();
};

const currentChange = (value: number) => {
    if (state.totalPage == value) {
        ElMessage.error('没有更多的信息');
    }
    getList();
};

// 查询按钮
const submitFn = () => {
    getList();
};

// 控制显示添加弹出框
const addUser = () => {
    showEditUser.value = true;
};

const hideDialog = () => {
    showEditUser.value = false;
    editId.value = 0;
};

// 解构
let { tableData, listParams, total } = toRefs(state);
</script>
<style lang="less" scoped>
/deep/.cell {
    text-align: center;
}

/deep/.el-table_1_column_1 {
    text-align: center;
}

.add-box {
    display: flex;
    justify-content: flex-end;
    padding: 10px;
    margin: 20px 0;
    border-radius: 10px;
    box-shadow: 0 0 4px 2px #ccc;
}

.search-box {
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 10px;

    .flex {
        display: flex;
        justify-content: space-between;
    }
}
</style>
